/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ty.cust;

import android.app.Service;
import android.content.ComponentName;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.content.Intent;
import android.os.IBinder;
import com.android.internal.telephony.ITelephony;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.PhoneFactory;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.Handler;
import android.os.Message;
import android.os.AsyncResult;
import android.widget.Toast;
import java.util.Locale;
import android.os.SystemProperties;
import android.telephony.SubscriptionManager;

public class MainService extends Service {
	private static final String TAG = "checkIMEI";
	private static final int CHECK_IMEI_SIM1 = 0;
	private static final int CHECK_IMEI_SIM2 = 1;
	private static final String IMEI_STATIC_STR = "355637";
	private static final int IMEI_DYNAMIC_MIN = 0;
	private static final int IMEI_DYNAMIC_MAX = 999999999;
	private static int mRetryTimes;
	private static final int RETRY_TIME_MAX = 10;
	private static final int RETRY_TIME_GAP = 100;
	private static String mRandomIMEI1Str;
	private static String mRandomIMEI2Str;

	private static final int CHECK_IMEI_ERROR = -1;
	private static final int CHECK_IMEI_VALID = 1;
	private static final int CHECK_IMEI_INVALID = 2;

	private static final String IMEI_ORIG_STR = "356986022066542";
	private static final boolean MTK_GEMINI_SUPPORT =
            "1".equals(SystemProperties.get("ro.mtk_gemini_support"));
	
	@Override
	public void onCreate() {
		super.onCreate();

		initCheckIMEI();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	private void disableSelf(){
		ComponentName name = new ComponentName(this, MainService.class);
		PackageManager pm = getPackageManager();
		pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
			PackageManager.DONT_KILL_APP);
	}

	private long getRandomInt(int min, int max){
		return Math.round(Math.random()*(max-min)+min);
	}

	private String getRandomIntString(long value){
		return String.format(Locale.ENGLISH,"%09d",value);
	}

	private String getRandomIMEIStr(long randomValue){
		return IMEI_STATIC_STR+getRandomIntString(randomValue);
	}

	private int doCheckIMEI(int simId, String strIMEI){
		Log.i(TAG, "checkIMEI simId="+simId+",strIMEI="+strIMEI);
		Phone phone = PhoneFactory.getDefaultPhone();
		if (phone == null) {
			Log.i(TAG, "phone == null");
			return CHECK_IMEI_ERROR;
		}
		String imei = phone.getDeviceId();
		Log.i(TAG, "exists IMEI = " + imei);
		if(imei == null || imei.length() == 0 || IMEI_ORIG_STR.equals(imei)){
			String imeiString[] = { "AT+EGMR=1,", "" };
			if (MTK_GEMINI_SUPPORT && (simId == CHECK_IMEI_SIM2)) {
				imeiString[0] = "AT+EGMR=1,10,\""+ strIMEI + "\"";
			}else{
				imeiString[0] = "AT+EGMR=1,7,\"" + strIMEI+ "\"";
			}
			Log.v(TAG, "IMEI String:" + imeiString[0]);
			phone.invokeOemRilRequestStrings(imeiString, mResponseHander.obtainMessage((simId == CHECK_IMEI_SIM2) ? EVENT_WRITE_IMEI2 : EVENT_WRITE_IMEI1));
			return CHECK_IMEI_INVALID;
		}
		return CHECK_IMEI_VALID;
	}

	private void finishCheckIMEI(){
		if(MTK_GEMINI_SUPPORT){
			initCheckIMEIGemini();
		}else{
			disableSelf();
		}
	}

	private void checkIMEI(){
		if(mRetryTimes > RETRY_TIME_MAX){
			finishCheckIMEI();
			return;
		}
		int result = doCheckIMEI(CHECK_IMEI_SIM1,mRandomIMEI1Str);
		mRetryTimes++;
		if(result == CHECK_IMEI_VALID){
			finishCheckIMEI();
		}else{
			if(result == CHECK_IMEI_ERROR){
				mResponseHander.sendEmptyMessageDelayed(EVENT_DELAY_CHECK_IMEI1,RETRY_TIME_GAP);
			}
		}
	}

	private void initCheckIMEI(){
		long sim1RandomIMEI = getRandomInt(IMEI_DYNAMIC_MIN,IMEI_DYNAMIC_MAX);
		mRandomIMEI1Str = getRandomIMEIStr(sim1RandomIMEI);
		if (MTK_GEMINI_SUPPORT) {
			for(;;){
				long sim2RandomIMEI = getRandomInt(IMEI_DYNAMIC_MIN,IMEI_DYNAMIC_MAX);
				if(sim2RandomIMEI == sim1RandomIMEI){
					continue;
				}
				mRandomIMEI2Str = getRandomIMEIStr(sim2RandomIMEI);
				break;
			}
		}

		mRetryTimes = 0;
		checkIMEI();
	}

	private int doCheckIMEIGemini(int simId, String strIMEI){
		if (!MTK_GEMINI_SUPPORT) {
			return CHECK_IMEI_VALID;
		}
		//try{
		 	//SubscriptionManager.setDefaultSubId(SubscriptionManager
            //                    .getSubIdUsingPhoneId(1));
		//} catch (RemoteException e) {
			//Log.i(TAG,"checkIMEI e="+e);
			//return CHECK_IMEI_ERROR;
		//}
		
		return doCheckIMEI(simId,strIMEI);
	}

	private void finishCheckIMEIGemini(){
		disableSelf();
	}

	private void checkIMEIGemini(){
		if(mRetryTimes > RETRY_TIME_MAX){
			disableSelf();
			return;
		}
		int result = doCheckIMEIGemini(CHECK_IMEI_SIM2,mRandomIMEI2Str);
		mRetryTimes++;
		if(result == CHECK_IMEI_VALID){
			disableSelf();
		}else{
			if(result == CHECK_IMEI_ERROR){
				mResponseHander.sendEmptyMessageDelayed(EVENT_DELAY_CHECK_IMEI2,RETRY_TIME_GAP);
			}
		}
	}

	private void initCheckIMEIGemini(){
		mRetryTimes = 0;
		checkIMEIGemini();
	}

	private static final int EVENT_WRITE_IMEI1 = 1;
	private static final int EVENT_WRITE_IMEI2 = 2;
	private static final int EVENT_DELAY_CHECK_IMEI1 = 3;
	private static final int EVENT_DELAY_CHECK_IMEI2 = 4;
	private Handler mResponseHander = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			AsyncResult ar;
			switch (msg.what) {
				case EVENT_WRITE_IMEI1:
		                    ar = (AsyncResult) msg.obj;
		                    if (ar.exception == null) {
		                        Log.i(TAG,"write imei success");
					     finishCheckIMEI();
		                    } else {
		                        Log.i(TAG,"write imei fail,mRetryTimes="+mRetryTimes);
		                        checkIMEI();
		                    }
					break;
				case EVENT_WRITE_IMEI2:
		                    ar = (AsyncResult) msg.obj;
		                    if (ar.exception == null) {
		                        Log.i(TAG,"write imei success");
					     finishCheckIMEIGemini();
		                    } else {
		                        Log.i(TAG,"write imei fail,mRetryTimes="+mRetryTimes);
		                        checkIMEIGemini();
		                    }
					break;
				case EVENT_DELAY_CHECK_IMEI1:
					checkIMEI();
					break;
				case EVENT_DELAY_CHECK_IMEI2:
					checkIMEIGemini();
					break;
				default:
					break;
			}
		}
	};
}

